﻿import 'package:get/get.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';
import 'package:azring/core/repository/default_api.dart';
import 'menstrual_cycle_setup_state.dart';

/// 生理周期设置控制器
class MenstrualCycleSetupLogic extends GetxController {
  final MenstrualCycleSetupState state = MenstrualCycleSetupState();

  @override
  void onInit() {
    super.onInit();
    initializeDefaultValues();
    loadSavedSettings();
  }

  /// 初始化默认值
  void initializeDefaultValues() {
    state.periodDays.value = '请选择';
    state.cycleDays.value = '请选择';
    state.lastPeriodDate.value = '请选择';
  }

  /// 加载已保存的设置
  Future<void> loadSavedSettings() async {
    try {
      final result = await DefaultApi().querySetInfoGet<Map<String, dynamic>>();

      if (result != null && result['code'] == 200 && result['data'] != null) {
        final data = result['data'];

        // 设置经期天数
        if (data['menstrualPeriodDays'] != null) {
          state.periodDays.value = '${data['menstrualPeriodDays']}天';
        }

        // 设置周期天数
        if (data['periodDays'] != null) {
          state.cycleDays.value = '${data['periodDays']}天';
        }

        // 设置上次月经日期
        if (data['startDate'] != null) {
          final dateString = data['startDate'] as String;
          final dateParts = dateString.split('-');
          if (dateParts.length == 3) {
            final year = dateParts[0];
            final month = dateParts[1];
            final day = dateParts[2];
            state.lastPeriodDate.value = '$year年$month月$day日';
          }
        }
      }
    } catch (e) {
      // 如果加载失败，保持默认值
      print('加载生理周期设置失败: $e');
    }
  }

  /// 检查设置是否完成
  bool isSetupComplete() {
    return state.periodDays.value != '请选择' &&
        state.cycleDays.value != '请选择' &&
        state.lastPeriodDate.value != '请选择';
  }

  /// 完成设置
  Future<void> completeSetup() async {
    final periodDaysInt =
        int.tryParse(state.periodDays.value.replaceAll('天', '')) ?? 5;
    final cycleDaysInt =
        int.tryParse(state.cycleDays.value.replaceAll('天', '')) ?? 28;
    final lastPeriodDateString = state.lastPeriodDate.value;

    DateTime? startDate;
    if (lastPeriodDateString != '请选择') {
      final regex = RegExp(r'(\d+)年(\d+)月(\d+)日');
      final match = regex.firstMatch(lastPeriodDateString);
      if (match != null && match.groupCount >= 3) {
        final yearStr = match.group(1);
        final monthStr = match.group(2);
        final dayStr = match.group(3);

        if (yearStr != null && monthStr != null && dayStr != null) {
          try {
            final year = int.parse(yearStr);
            final month = int.parse(monthStr);
            final day = int.parse(dayStr);
            startDate = DateTime(year, month, day);
          } catch (e) {
            print('日期解析失败: $e');
            startDate = DateTime.now();
          }
        }
      }
    }

    // 如果 startDate 仍然为 null，使用当前日期
    startDate ??= DateTime.now();

    // 格式化日期为 yyyy-MM-dd
    final formattedDate =
        '${startDate.year}-${startDate.month.toString().padLeft(2, '0')}-${startDate.day.toString().padLeft(2, '0')}';

    // 调用 API 保存生理周期设置
    final result = await DefaultApi().setInfoPost<Map<String, dynamic>>(
      menstrualPeriodDays: periodDaysInt.toString(),
      periodDays: cycleDaysInt.toString(),
      startDate: formattedDate,
    );
    print(result != null && result['code'] == 200);
    if (result != null && result['code'] == 200) {
      Toast.show('设置成功');
      // 使用 offNamed 替换当前页面，确保日历页重新初始化
      Get.offNamed('/menstrual-cycle/calendar');
    } else {
      final errorMsg = result?['msg'] ?? '设置失败';
      Toast.show(errorMsg);
    }
  }

  /// 重置设置
  void resetSetup() {
    state.periodDays.value = '请选择';
    state.cycleDays.value = '请选择';
    state.lastPeriodDate.value = '请选择';
  }
}
